package controll

import (
	"fmt"
	util "haodayizhi/utils"
	"net/http"
	"sync"

	"github.com/gin-gonic/gin"
)

var (
	// userConnections 维护用户 ID 到 SSE 连接的映射
	userConnections = make(map[int64]chan string)
	mu              sync.RWMutex
)

// 事件名称
const (
	EventNameMessage = "new_notice"
	EventNameError   = "error"
	EventNameClose   = "close"
)

// 获取用户连接
func GetUserConnection(userID int64) (chan string, bool) {
	mu.RLock()
	defer mu.RUnlock()
	conn, ok := userConnections[userID]
	return conn, ok
}

// 保存用户连接
func SetUserConnection(userID int64, conn chan string) {
	mu.Lock()
	defer mu.Unlock()
	userConnections[userID] = conn
}

// 删除用户连接
func DeleteUserConnection(userID int64) {
	mu.Lock()
	defer mu.Unlock()
	delete(userConnections, userID)
}

// SSE 处理程序
func SSEHandler(c *gin.Context) {
	tokenConfig, err := util.GetTokenInfo(c)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
		return
	}

	c.Header("Content-Type", "text/event-stream")
	c.Header("Cache-Control", "no-cache")
	c.Header("Connection", "keep-alive")

	messageChannel := make(chan string)
	SetUserConnection(tokenConfig.UserID, messageChannel)

	go func() {
		for msg := range messageChannel {
			c.SSEvent(EventNameMessage, msg)
		}
		DeleteUserConnection(tokenConfig.UserID)
	}()

	// Keep the connection open
	<-c.Request.Context().Done()
}

// SendMessageToAllUsers 向所有连接的用户推送消息
func SendMessageToAllUsers(message string) {
	mu.RLock()
	defer mu.RUnlock()
	for _, conn := range userConnections {
		fmt.Println(message)
		fmt.Println(conn)
		conn <- message
	}
}
